package com.up.upzl.base.config;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by zouwei on 2017/10/26.
 */
@Slf4j
public final class JsonUtil {

	private static final String PATTERN = "yyyy/MM/dd HH:mm:ss";

	private JsonUtil() {

	}

	/**
	 * mapper : 转换器
	 */
	private static final ObjectMapper objectMapper;

	static {
		objectMapper = new ObjectMapper();
		objectMapper.setDateFormat(new SimpleDateFormat(PATTERN));
	}

	/**
	 * 将对象转换成json字符串
	 *
	 * @param data
	 * @return
	 * @throws JsonProcessingException
	 */
	public static <T> String getJsonString(T data) throws JsonProcessingException {
		if (data == null) {
			return null;
		}
		if (data instanceof Collection) {
			Collection d = (Collection) data;
			if (CollectionUtils.isEmpty(d)) {
				return null;
			}
		}
		return objectMapper.writeValueAsString(data);
	}

	/**
	 * 将对象转换成json字符串
	 *
	 * @param data
	 * @param pattern
	 * @param <T>
	 * @return
	 * @throws JsonProcessingException
	 */
	public static <T> String getJsonString(T data, String pattern) throws JsonProcessingException {
		if (data == null) {
			return null;
		}
		if (data instanceof Collection) {
			Collection d = (Collection) data;
			if (CollectionUtils.isEmpty(d)) {
				return null;
			}
		}
		/**
		 * 需要重新创建ObjectMapper，否则线程不安全
		 */
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setDateFormat(new SimpleDateFormat(pattern));
		return objectMapper.writeValueAsString(data);
	}

	/**
	 * 把字符串转换成对象
	 *
	 * @param jsonString
	 * @param clazz
	 * @return
	 * @throws IOException,JsonProcessingException
	 */
	public static <T> T parseStringToObject(String jsonString, Class<T> clazz)
			throws IOException, JsonProcessingException {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}
		return objectMapper.readValue(jsonString, clazz);
	}

	/**
	 * 把字符串转换成对象
	 *
	 * @param jsonString
	 * @param clazz
	 * @param pattern
	 * @param <T>
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 */
	public static <T> T parseStringToObject(String jsonString, Class<T> clazz, String pattern)
			throws IOException, JsonProcessingException {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}
		/**
		 * 需要重新创建ObjectMapper，否则线程不安全
		 */
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setDateFormat(new SimpleDateFormat(pattern));
		return objectMapper.readValue(jsonString, clazz);
	}
}
